//校验用户是否登录
checkLogin()
//渲染用户登录
randerUsername()
//退出登录
logOut()
//数据渲染
render()
async function render() {

    // const token = getItem('token')
    // console.log(token);
    const { data } = await axios('/students')
    document.querySelector('.total').innerHTML = data.length;
    // console.log(data);
    const xingbie = ['男', '女']
    document.querySelector('.list').innerHTML = data.map(item => `
                    <tr>
                      <td>${item.name}</td>
                      <td>${item.age}</td>
                      <td>${xingbie[item.gender]}</td>
                      <td>第${item.group}组</td>
                      <td>${item.hope_salary}</td>
                      <td>${item.salary}</td>
                      <td>${item.province}${item.city}${item.area}</td>
                      <td data-id='${item.id}'>
                        <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
                        <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
                      </td>
                    </tr>
    `).join('')
}

//添加

const openModal = document.querySelector('#openModal')
const myModalAlternative = new bootstrap.Modal('#modal')
openModal.addEventListener('click', () => {
    const form = document.querySelector('#form');
    form.reset()
    document.querySelector('.modal-title').innerHTML = '添加学员';
    initprovince()
    myModalAlternative.edited = null
    myModalAlternative.show()
})
// document.querySelector('.page-content .ml-4').addEventListener('click', function () {
//     myModalAlternative.show()
//     // const form = document.querySelector('.g-3 row');
//     // const data = serialize(form, { hash: true, empty: true })
//     // console.log(data);
//     initprovince()
// })

//获取省份
const province = document.querySelector('[name=province]');
const city = document.querySelector('[name=city]');
const area = document.querySelector('[name=area]');

async function initprovince() {
    const res = await axios('/api/province')
    let str = res.list.map(item => `<option value="${item}">--${item}--</option>`)
    province.innerHTML = `<option value="">--省份--</option>` + str
}
province.addEventListener('change', async function () {
    const pname = province.value
    const res = await axios({ url: '/api/city', params: { pname } })
    let str = res.list.map(item => `<option value="${item}">--${item}--</option>`)
    city.innerHTML = `<option value="">--城市--</option>` + str
})

city.addEventListener('change', async function () {
    const pname = province.value
    const cname = city.value
    const res = await axios({ url: '/api/area', params: { pname, cname } })
    let str = res.list.map(item => `<option value="${item}">--${item}--</option>`)
    area.innerHTML = `<option value="">--地区--</option>` + str
})

document.querySelector('#submit').addEventListener('click', async function () {
    const form = document.querySelector('#modal form');
    let data = serialize(form, { hash: true, empty: true })
    console.log(data);
    data.age = Number(data.age)
    data.gender = Number(data.gender)
    data.group = Number(data.group)
    data.hope_salary = Number(data.hope_salary)
    data.salary = Number(data.salary)

    if (myModalAlternative.edited) {
        const id = myModalAlternative.edited
        // console.log(myModalAlternative.edited);
        try {
            const res = await axios({ method: 'put', url: `/students/${id}`, data })
            // console.log(res);
            // showToast(res.message)
            render()
            myModalAlternative.hide()
            form.reset()
            document.querySelector('.sub')?.classList.remove('sub');

        } catch (error) {
            const reg = /[a-zA-z]+/
            const key = reg.exec(error.response.data.message)
            // document.querySelector(`[name=${key}]`).value=''
            // document.querySelector(`[name=${key}]`).classList.add('red')
            document.querySelector(`[name=${key}]`).classList.add('apply-shake')
            setTimeout(() => {
                document.querySelector(`[name=${key}]`).classList.remove('apply-shake')
            }, 820);
            document.querySelector(`[name=${key}]`).addEventListener('focus', () => {
                document.querySelector(`[name=${key}]`).classList.remove('red')
            })
            // showToast(error.response.data.message)
        }
        // alert('编辑')
    } else {
        try {
            const res = await axios({ method: 'post', url: '/students', data })
            // console.log(res);
            showToast(res.message)
            render()
            myModalAlternative.hide()
            form.reset()
            document.querySelector('.sub')?.classList.remove('sub');
        } catch (error) {
            const reg = /[a-zA-z]+/
            const key = reg.exec(error.response.data.message)
            // document.querySelector(`[name=${key}]`).value=''
            document.querySelector(`[name=${key}]`).classList.add('red')
            document.querySelector(`[name=${key}]`).classList.add('apply-shake')
            setTimeout(() => {
                document.querySelector(`[name=${key}]`).classList.remove('apply-shake')
            }, 820);
            document.querySelector(`[name=${key}]`).addEventListener('focus', () => {
                document.querySelector(`[name=${key}]`).classList.remove('red')
            })
            // showToast(error.response.data.message)
        }
    }
})


//删除
document.querySelector('.list').addEventListener('click', async (e) => {
    // console.log('点击率');
    if (e.target.classList.contains('bi-trash')) {
        const id = e.target.parentNode.parentNode.dataset.id
        // console.log(id);
        const res = await axios({ method: 'delete', url: `/students/${id}` })
        // console.log(res);
        render()
    } else if (e.target.classList.contains('bi-pen')) {
        const id = e.target.parentNode.parentNode.dataset.id
        edit(id)
    }
});

//数据回显

async function edit(id) {
    myModalAlternative.edited = id
    document.querySelector('.modal-title').innerHTML = '修改信息';
    const res = await axios(`/students/${id}`)
    const keyArr = Object.keys(res.data)
    // console.log(keyArr);
    keyArr.forEach(key => {
        if (key == 'gender') {
            const index = res.data[key]
            document.querySelectorAll('[name=gender]')[index].checked = true
        } else {
            const ele = document.querySelector(`form [name=${key}]`)
            if (ele) ele.value = res.data[key]
        }
    })
    const pdata = await axios('/api/province')
    let wstr = pdata.list.map(item => `<option value="${item}">--${item}--</option>`)
    province.innerHTML = `<option value="">--省份--</option>` + wstr

    province.value = res.data.province
    const cdata = await axios({ url: '/api/city', params: { pname: res.data.province } })
    let str = cdata.list.map(item => `<option value="${item}">--${item}--</option>`)
    city.innerHTML = `<option value="">--城市--</option>` + str
    city.value = res.data.city

    const adata = await axios({ url: '/api/area', params: { pname: res.data.province, cname: res.data.city } })
    let pstr = adata.list.map(item => `<option value="${item}">--${item}--</option>`)
    area.innerHTML = `<option value="">--地区--</option>` + pstr
    area.value = res.data.area
    myModalAlternative.show()

}

// document.querySelector('.list').addEventListener('click', async (e) => {
//     if (!e.target.classList.contains('bi-pen')) return
//     const myModalAlternative = new bootstrap.Modal('#modal')
//     document.querySelector('.modal-title').innerHTML = '修改信息';
//     const id = e.target.parentNode.parentNode.dataset.id
//     myModalAlternative.edited = id
//     const res = await axios(`/students/${id}`)
//     // myModalAlternative.show()
//     const keyArr = Object.keys(res.data)
//     keyArr.forEach(key => {
//         document.querySelector(`[name=${key}]`).value = res.data[key]
//     })
//     if (res.data.gender == '0') {
//         document.querySelector('#cb01').checked = true;
//     } else { document.querySelector('#cb02').checked = true }
//     // console.log(res);
//     initprovince()
//     province.value = res.data.province

//     const cdata = await axios({ url: '/api/city', params: { pname: res.data.province } })
//     let str = cdata.list.map(item => `<option value="${item}">--${item}--</option>`)
//     city.innerHTML = `<option value="">--城市--</option>` + str
//     city.value = res.data.city

//     const adata = await axios({ url: '/api/area', params: { pname, cname } })
//     let pstr = adata.list.map(item => `<option value="${item}">--${item}--</option>`)
//     area.innerHTML = `<option value="">--地区--</option>` + pstr
//     area.value = res.data.area


// })



